<?php 
/**
*  * 系统-受国家计算机软件著作权保护 - !
* =========================================================
* Copy right 2018-2025 成都海之心科技有限公司, 保留所有权利。
* ----------------------------------------------
* 官方网址: http://www.ohyu.cn
* 这不是一个自由软件！在未得到官方有效许可的前提下禁止对程序代码进行修改和使用。
* 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
* =========================================================
* User: ohyueo
* Date: 2024/04/17
* Time: 21:45
*/
namespace app\admin\controller;
use app\admin\models\EscortMerchantMerlist;
use EasyWeChat\Factory;
use think\facade\View;
use think\facade\Db;
use app\admin\traits\AdminAuth;

use app\admin\models\EscortWxopenDraft;
use app\admin\models\EscortWxopenGetauthorizerlist;
use PHPExcel_IOFactory;
use PHPExcel;
use app\admin\models\EscortWxopenCodelist;
use app\admin\models\EscortUserList;
use EasyWeChat\Kernel\Http\Response;

class Wxopen extends Common{
	use AdminAuth;

	public function codelist(){
 		$dao=input('param.dao');
		if(request()->isPost() || $dao==1){
			$page=input('param.page');
			if(!$page){
				$page=1;
			}
			$limit=input('param.limit');
			if(!$limit){
				$limit=10;//每页显示条数
			}
			$where=[];
			$id=input('param.id');
			if($id){
				$where[]=['id','=',$id];
			}
			$template_id=input('param.template_id');
			if($template_id){
				$where[]=['template_id','like','%'.$template_id.'%'];
			}
			$user_version=input('param.user_version');
			if($user_version){
				$where[]=['user_version','like','%'.$user_version.'%'];
			}
			$user_desc=input('param.user_desc');
			if($user_desc){
				$where[]=['user_desc','like','%'.$user_desc.'%'];
			}
			$template_type=input('param.template_type');
			if($template_type){
				$where[]=['template_type','like','%'.$template_type.'%'];
			}
			$source_miniprogram_appid=input('param.source_miniprogram_appid');
			if($source_miniprogram_appid){
				$where[]=['source_miniprogram_appid','like','%'.$source_miniprogram_appid.'%'];
			}
			$source_miniprogram=input('param.source_miniprogram');
			if($source_miniprogram){
				$where[]=['source_miniprogram','like','%'.$source_miniprogram.'%'];
			}
			$category_list=input('param.category_list');
			if($category_list){
				$where[]=['category_list','like','%'.$category_list.'%'];
			}
			$audit_scene=input('param.audit_scene');
			if($audit_scene){
				$where[]=['audit_scene','like','%'.$audit_scene.'%'];
			}
			$audit_status=input('param.audit_status');
			if($audit_status){
				$where[]=['audit_status','like','%'.$audit_status.'%'];
			}
			$reason=input('param.reason');
			if($reason){
				$where[]=['reason','like','%'.$reason.'%'];
			}
			$addtime=input('param.addtime');
			if($addtime){
				$where[]=['addtime','like','%'.$addtime.'%'];
			}
			$count = EscortWxopenCodelist::where($where)->count();
			if($dao!=1){
				$data=EscortWxopenCodelist::where($where)->page($page,$limit)->order('id desc')->select()->toArray();
			}
			if($dao==1){
				$data=EscortWxopenCodelist::where($where)->order('id desc')->select()->toArray();
			}
			$url=getweburl();
			//去掉url中的http://或https://
			$url=str_replace('http://','',$url);
			$url=str_replace('https://','',$url);
			$url=str_replace('/','',$url);
			if($data){
				for($i=0;$i<count($data);$i++){
					$user_version=$data[$i]['user_version'];
					//查询这个appid是多少
					$authinfo=EscortWxopenGetauthorizerlist::where('authorizer_appid',$data[$i]['source_miniprogram_appid'])->find();
					$merid=$authinfo['id'];
					$data[$i]['merid']=$merid;

					$ext='"host": "'.$url.'","appid": "'.$data[$i]['source_miniprogram_appid'].'","version":"'.$user_version.'","merid": "'.$merid.'"';
					$data[$i]['ext']=$ext;
				}
			}
			if($dao==1){
				$excel = new \PHPExcel(); //引用phpexcel
				$excel->setActiveSheetIndex(0);
				$namex = '代码模板库';
				$excel->getActiveSheet()->setTitle($namex); //设置表名
				$excel->getActiveSheet()->getDefaultColumnDimension()->setWidth(20);//所有单元格（列）默认宽度
				$excel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(50);
				$excel->getDefaultStyle()->getFont()->setName('微软雅黑');//字体
				$styleThinBlackBorderOutline = array(
				'borders' => array(
				'allborders' => array( //设置全部边框
				'style' => \PHPExcel_Style_Border::BORDER_THIN //粗的是thick
				)
				),
				);
				// 设置单元格的宽度
				$excel->getActiveSheet()->getDefaultColumnDimension()->setWidth(20);
				$excel->setActiveSheetIndex(0)
				->setCellValue('A1', 'ID')
				->setCellValue('B1', '模板id')
				->setCellValue('C1', '版本号')
				->setCellValue('D1', '版本描述')
				->setCellValue('E1', '模板类型')
				->setCellValue('F1', '小程序appid')
				->setCellValue('G1', '小程序名称')
				->setCellValue('H1', '类目信息')
				->setCellValue('I1', '场景标签')
				->setCellValue('J1', '状态')
				->setCellValue('K1', '失败原因')
				->setCellValue('L1', '添加时间')
				;
				$excel->getActiveSheet()->getStyle( 'A1:L1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
				$excel->getActiveSheet()->getStyle( 'A1:L1')->getFill()->getStartColor()->setARGB('FCE4D6');//设置填充颜色
				$cno=count($data)+1;
				$excel->getActiveSheet()->getStyle('A1:L'.$cno)->applyFromArray($styleThinBlackBorderOutline);
				foreach ($data as $k => $v) {
				$excel->getActiveSheet()->setCellValue('A' . ($k + 2), $v['id']."	");
					$excel->getActiveSheet()->setCellValue('B' . ($k + 2), $v['template_id']);
					$excel->getActiveSheet()->setCellValue('C' . ($k + 2), $v['user_version']);
					$excel->getActiveSheet()->setCellValue('D' . ($k + 2), $v['user_desc']);
					$excel->getActiveSheet()->setCellValue('E' . ($k + 2), $v['template_type']);
					$excel->getActiveSheet()->setCellValue('F' . ($k + 2), $v['source_miniprogram_appid']);
					$excel->getActiveSheet()->setCellValue('G' . ($k + 2), $v['source_miniprogram']);
					$excel->getActiveSheet()->setCellValue('H' . ($k + 2), $v['category_list']);
					$excel->getActiveSheet()->setCellValue('I' . ($k + 2), $v['audit_scene']);
					$excel->getActiveSheet()->setCellValue('J' . ($k + 2), $v['audit_status']);
					$excel->getActiveSheet()->setCellValue('K' . ($k + 2), $v['reason']);
					$excel->getActiveSheet()->setCellValue('L' . ($k + 2), $v['addtime']);
				}
				ob_end_clean();
				header('Content-Type: application/vnd.ms-excel');
				header('Content-Disposition: attachment;filename="' . $namex . '.xls"');
				header('Cache-Control: max-age=0');
				$res_excel = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
				$res_excel->save('php://output');exit;
			}
			$res = ["data" => $data,"code"=>0,'message'=>'请求成功','count'=>$count];
			return json($res);
		}
		$permis = $this->getPermissions('Wxopen/codelist');
		View::assign('data', $this->actions);
		View::assign('permis', $permis);
		return View::fetch();
	}
	public function addcodelist(){
 		if(request()->isPost()){
			$data = array('status' => 0, 'msg' => '未知错误');
			$type=input('param.type');
			if($type==1){
				//使用WxOpen获取getTemplateList
				$wxopen = new \app\common\WxOpen();
				$res=$wxopen->getCodeTemplateList();
				if($res){
					$list=$res['template_list'];
					for($i=0;$i<count($list);$i++){
						$template_id=$list[$i]['template_id'];
						$draft_id=$list[$i]['draft_id'];
						$user_version=$list[$i]['user_version'];
						$user_desc=$list[$i]['user_desc'];
						$template_type=$list[$i]['template_type'];
						$source_miniprogram_appid=$list[$i]['source_miniprogram_appid'];
						$source_miniprogram=$list[$i]['source_miniprogram'];
						$category_list=$list[$i]['category_list'];
						$audit_scene=isset($list[$i]['audit_scene'])?$list[$i]['audit_scene']:'';
						$audit_status=isset($list[$i]['audit_status'])?$list[$i]['audit_status']:'';
						$reason=isset($list[$i]['reason'])?$list[$i]['reason']:'';
						$addtime=date('Y-m-d H:i:s',$list[$i]['create_time']);
						$arr=array(
							'template_id'=>$template_id,
							'draft_id'=>$draft_id,//'draft_id'=>'草稿id
							'user_version'=>$user_version,
							'user_desc'=>$user_desc,
							'template_type'=>$template_type,
							'source_miniprogram_appid'=>$source_miniprogram_appid,
							'source_miniprogram'=>$source_miniprogram,
							'category_list'=>$category_list,
							'audit_scene'=>$audit_scene,
							'audit_status'=>$audit_status,
							'reason'=>$reason,
						);
						//判断是否已经存在
						$exist=EscortWxopenCodelist::where('template_id',$list[$i]['template_id'])->find();
						if($exist){
							//修改
							EscortWxopenCodelist::where('template_id',$template_id)->update($arr);
							$text = '修改了代码模板库-id='.$exist['id'];
							$this->writeActionLog($text);
						}else{
							//添加
							$arr['addtime']=$addtime;
							$id=EscortWxopenCodelist::insertGetId($arr);
							$text = '添加了代码模板库-id='.$id;
							$this->writeActionLog($text);
						}
					}
					$data['status'] = 1;
					return json($data);exit;
				}
			}
			

			$template_id=input('param.template_id');
			$user_version=input('param.user_version');
			$user_desc=input('param.user_desc');
			$template_type=input('param.template_type');
			$source_miniprogram_appid=input('param.source_miniprogram_appid');
			$source_miniprogram=input('param.source_miniprogram');
			$category_list=input('param.category_list');
			$audit_scene=input('param.audit_scene');
			$audit_status=input('param.audit_status');
			$reason=input('param.reason');
			$addtime=input('param.addtime');
			$arr=array(
				'template_id'=>$template_id,
				'user_version'=>$user_version,
				'user_desc'=>$user_desc,
				'template_type'=>$template_type,
				'source_miniprogram_appid'=>$source_miniprogram_appid,
				'source_miniprogram'=>$source_miniprogram,
				'category_list'=>$category_list,
				'audit_scene'=>$audit_scene,
				'audit_status'=>$audit_status,
				'reason'=>$reason,
				'addtime'=>$addtime,
			);
			$id=EscortWxopenCodelist::insertGetId($arr);
			$text = '添加了代码模板库-id='.$id;
			$this->writeActionLog($text);
			$data['status'] = 1;
			return json($data);exit;
		}
		return View::fetch('editcodelist');
	}
	public function editcodelist(){
 		if(request()->isPost()){
			$user_version=input('param.user_version');
			$user_desc=input('param.user_desc');
			$ext_json=input('param.ext_json');
			$id = input('param.id');
			if ($id){
                $codeInfo = EscortWxopenCodelist::find($id);
                $wxOpenMethod = new \app\common\WxOpen();
                $auth_info = EscortWxopenGetauthorizerlist::where('authorizer_appid',$codeInfo['source_miniprogram_appid'])->find();
//                $ext_json = json_encode($ext_json,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
                $ext_json = json_decode(htmlspecialchars_decode($ext_json),true);

                $ext_json = json_encode($ext_json,true);
                $res = $wxOpenMethod->commitCode($auth_info['authorizer_appid'],$auth_info['refresh_token'],$codeInfo['template_id'],$ext_json,$user_version,$user_desc);
                if($res['errcode'] == 0){
                    $id=EscortWxopenCodelist::where('id',$id)->update(['audit_status'=>3]);
                    $text = '修改了代码模板库-id='.$id;
                    $this->writeActionLog($text);
                    $data = ['status'=>1,'msg'=>'操作成功'];
                }else {
                    $data = ['status'=>0,'msg'=>$res['errmsg']];
                }
				return json($data);
			}
		}
		return View::fetch('editcodelist');
	}

    //提交审核
    public function submitAudit()
    {
        $id = input('param.id');
        if(empty($id)) {
            return ['status' => 0, 'msg' => '参数错误'];
        }
        //查询codelist信息
        $code_info = EscortWxopenCodelist::find($id);
        $auth_info = EscortWxopenGetauthorizerlist::where('authorizer_appid',$code_info['source_miniprogram_appid'])->find();
        $wxOpenMethod = new \app\common\WxOpen();

        $res = $wxOpenMethod->getCategory($auth_info['authorizer_appid'],$auth_info['refresh_token']);
        $response = [
            'feedback_info'     => '',
            'feedback_stuff'    => '',
            'version_desc'      => $code_info['user_desc'],
        ];
        foreach($res['category_list'] as $val) {
            $item_list[] = [
                'address'       => '',
                'tag'           => '',
                'first_class'   => $val['first_class'],
                'second_class'  => $val['second_class'],
                'first_id'      => $val['first_id'],
                'second_id'     => $val['second_id'],
                'title'         => '',
            ];
        }
        $response['item_list'] = $item_list;
        $res = $wxOpenMethod->submitAudit($auth_info['authorizer_appid'],$auth_info['refresh_token'],$response);
        if($res['errcode'] == 0){
            EscortWxopenCodelist::where('id',$id)->update(['audit_status'=>4,'is_submit'=>1]);
            $data = ['status' => 1, 'msg' => '操作成功'];
        } else {
            $data = ['status' => 0, 'msg' => $res['errmsg']];
        }
        return json($data);
    }

    //获取体验版二维码
    public function experienceApplet()
    {
        $data = ['status' => 0, 'msg' => '参数错误'];
        $id   = input('param.id');
        $path = config('-shopsite.applet_homepage_path');
        if(empty($id) || empty($path)) {
           return $data;
        }
        $path = urlencode($path);
        //查询codelist信息
        $code_info = EscortWxopenCodelist::find($id);
        $auth_info = EscortWxopenGetauthorizerlist::where('authorizer_appid',$code_info['source_miniprogram_appid'])->find();
        $wxOpenMethod = new \app\common\WxOpen();
        $res = $wxOpenMethod->getQrcode($auth_info['authorizer_appid'],$auth_info['refresh_token'],$path);

        $result = json_decode($res,true);
        if(empty($result)) {
            $content = $res->getBodyContents();
            $file_name = 'uploads/qrcode/'.time().'.jpg';
            file_put_contents($file_name,$content);
            EscortWxopenCodelist::where('id',$id)->update(['thumb'=>$file_name]);
            $data = ['status' => 1, 'msg' => '生成成功'];
        } else {
            $data = ['status' => $result['errcode'], 'msg' => $result['errmsg']];
        }
        return json($data);
    }

    //发版
    public function publish()
    {
        $id   = input('param.id');
        if(empty($id)) return json(['status' => 0, 'msg' => '参数错误']);
        //查询codelist信息
        $code_info = EscortWxopenCodelist::find($id);
        $auth_info = EscortWxopenGetauthorizerlist::where('authorizer_appid',$code_info['source_miniprogram_appid'])->find();
        $wxOpenMethod = new \app\common\WxOpen();
        $res = $wxOpenMethod->publish($auth_info['authorizer_appid'],$auth_info['refresh_token']);
        if($res['errcode'] == 0){
            EscortWxopenCodelist::where('id',$id)->update(['is_publish'=>1]);
            $data = ['status' => 1, 'msg' => '操作成功'];
        } else {
            $data = ['status' => 0, 'msg' => $res['errmsg']];
        }
        return json($data);
    }

    public function undo()
    {
        $id   = input('param.id');
        if(empty($id) || empty($path)) return ['status' => 0, 'msg' => '参数错误'];
        //查询codelist信息
        $code_info = EscortWxopenCodelist::find($id);
        $auth_info = EscortWxopenGetauthorizerlist::where('authorizer_appid',$code_info['source_miniprogram_appid'])->find();
        $wxOpenMethod = new \app\common\WxOpen();
        $res = $wxOpenMethod->undoPublish($auth_info['authorizer_appid'],$auth_info['refresh_token']);
        if($res['errcode'] == 0){
            $data = ['status' => 1, 'msg' => '操作成功'];
        } else {
            $data = ['status' => 0, 'msg' => $res['errmsg']];
        }
        return json($data);
    }


	public function delcodelist(){
 		$data = array('status' => 0,'msg' => '未知错误');
		$array=input("param.id");
		if(!$array){
			$data['msg']='参数错误';return json($data);exit;
		}
		$arr=explode(",",$array);
		for($i=0;$i<count($arr);$i++){
			if($arr[$i]){
				EscortWxopenCodelist::where('id',$arr[$i])->delete();
				$text = '删除了代码模板库id='.$arr[$i].'的数据';
				$this->writeActionLog($text);
			}
		}
		$data['status']=1;
		return json($data);
	}
	public function getauthorizerlist(){
 		$dao=input('param.dao');
		if(request()->isPost() || $dao==1){
			$page=input('param.page');
			if(!$page){
				$page=1;
			}
			$limit=input('param.limit');
			if(!$limit){
				$limit=10;//每页显示条数
			}
			$where=[];
			$id=input('param.id');
			if($id){
				$where[]=['id','=',$id];
			}
			$authorizer_appid=input('param.authorizer_appid');
			if($authorizer_appid){
				$where[]=['authorizer_appid','like','%'.$authorizer_appid.'%'];
			}
			$refresh_token=input('param.refresh_token');
			if($refresh_token){
				$where[]=['refresh_token','like','%'.$refresh_token.'%'];
			}
			$auth_time=input('param.auth_time');
			if($auth_time){
				$where[]=['auth_time','like','%'.$auth_time.'%'];
			}
			$count = EscortWxopenGetauthorizerlist::where($where)->count();
			if($dao!=1){
				$data=EscortWxopenGetauthorizerlist::where($where)->page($page,$limit)->order('id desc')->select()->toArray();
			}
			if($dao==1){
				$data=EscortWxopenGetauthorizerlist::where($where)->order('id desc')->select()->toArray();
			}
			if($data){
				for($i=0;$i<count($data);$i++){
					//auth_time
					$data[$i]['auth_time']=date('Y-m-d H:i:s',$data[$i]['auth_time']);
					
					//查询授权详情表里面的昵称和头像
					$authinfo=Db::name('Escort_wxopen_authinfo')->where('authid',$data[$i]['id'])->find();
					if($authinfo){
						$data[$i]['nick_name']=$authinfo['nick_name'];
						$data[$i]['head_img']=isset($authinfo['head_img'])?$authinfo['head_img']:'';
						$data[$i]['service_type_info']=$authinfo['service_type_info'];
						$data[$i]['qrcode_url']=$authinfo['qrcode_url'];
						$data[$i]['type']=$authinfo['type'];
						$data[$i]['account_status']=$authinfo['account_status'];
						$data[$i]['isinfo']=1;
					}else{
						$data[$i]['nick_name']='';
						$data[$i]['head_img']='';
						$data[$i]['service_type_info']='';
						$data[$i]['qrcode_url']='';
						$data[$i]['type']='';
						$data[$i]['account_status']='';
						$data[$i]['isinfo']=0;
					}
				}
			}
			if($dao==1){
				$excel = new \PHPExcel(); //引用phpexcel
				$excel->setActiveSheetIndex(0);
				$namex = '授权列表';
				$excel->getActiveSheet()->setTitle($namex); //设置表名
				$excel->getActiveSheet()->getDefaultColumnDimension()->setWidth(20);//所有单元格（列）默认宽度
				$excel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(50);
				$excel->getDefaultStyle()->getFont()->setName('微软雅黑');//字体
				$styleThinBlackBorderOutline = array(
				'borders' => array(
				'allborders' => array( //设置全部边框
				'style' => \PHPExcel_Style_Border::BORDER_THIN //粗的是thick
				)
				),
				);
				// 设置单元格的宽度
				$excel->getActiveSheet()->getDefaultColumnDimension()->setWidth(20);
				$excel->setActiveSheetIndex(0)
				->setCellValue('A1', 'ID')
				->setCellValue('B1', '已授权账号的 appid')
				->setCellValue('C1', '刷新令牌authorizer_refresh_token')
				->setCellValue('D1', '授权的时间')
				;
				$excel->getActiveSheet()->getStyle( 'A1:D1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
				$excel->getActiveSheet()->getStyle( 'A1:D1')->getFill()->getStartColor()->setARGB('FCE4D6');//设置填充颜色
				$cno=count($data)+1;
				$excel->getActiveSheet()->getStyle('A1:D'.$cno)->applyFromArray($styleThinBlackBorderOutline);
				foreach ($data as $k => $v) {
				$excel->getActiveSheet()->setCellValue('A' . ($k + 2), $v['id']."	");
					$excel->getActiveSheet()->setCellValue('B' . ($k + 2), $v['authorizer_appid']);
					$excel->getActiveSheet()->setCellValue('C' . ($k + 2), $v['refresh_token']);
					$excel->getActiveSheet()->setCellValue('D' . ($k + 2), $v['auth_time']);
				}
				ob_end_clean();
				header('Content-Type: application/vnd.ms-excel');
				header('Content-Disposition: attachment;filename="' . $namex . '.xls"');
				header('Cache-Control: max-age=0');
				$res_excel = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
				$res_excel->save('php://output');exit;
			}
			$res = ["data" => $data,"code"=>0,'message'=>'请求成功','count'=>$count];
			return json($res);
		}
		$permis = $this->getPermissions('Wxopen/getauthorizerlist');
		View::assign('data', $this->actions);
		View::assign('permis', $permis);
		return View::fetch();
	}
	public function addgetauthorizerlist(){
 		if(request()->isPost()){
			$data = array('status' => 0, 'msg' => '未知错误');
			$type=input('param.type');
			if($type=='gengxin'){ //获取授权列表
				//引入WxOpen
				$wxopen = new \app\common\WxOpen();
				$res=$wxopen->getAuthList();
				if($res && $res['total_count']>0){
					$list=$res['list'];
					for($i=0;$i<count($list);$i++){
						$authorizer_appid=$list[$i]['authorizer_appid'];
						//判断是否已经存在
						$exist=EscortWxopenGetauthorizerlist::where('authorizer_appid',$authorizer_appid)->find();
						if($exist){
							continue;
						}
						$refresh_token=$list[$i]['refresh_token'];
						$auth_time=$list[$i]['auth_time'];
						$arr=array(
							'authorizer_appid'=>$authorizer_appid,
							'refresh_token'=>$refresh_token,
							'auth_time'=>$auth_time,
						);
						$id=EscortWxopenGetauthorizerlist::insertGetId($arr);
						$text = '添加了授权列表-id='.$id;
						$this->writeActionLog($text);
					}
					$data['status'] = 1;
					return json($data);exit;
				}
			}
			$authorizer_appid=input('param.authorizer_appid');
			$refresh_token=input('param.refresh_token');
			$auth_time=input('param.auth_time');
			$arr=array(
				'authorizer_appid'=>$authorizer_appid,
				'refresh_token'=>$refresh_token,
				'auth_time'=>$auth_time,
			);
			$id=EscortWxopenGetauthorizerlist::insertGetId($arr);
			$text = '添加了授权列表-id='.$id;
			$this->writeActionLog($text);
			$data['status'] = 1;
			return json($data);exit;
		}
		return View::fetch('editgetauthorizerlist');
	}
	public function editgetauthorizerlist(){
 		if(request()->isPost()){
			$data = array('status' => 0, 'msg' => '未知错误');
			$type=input('param.type');
			if($type=='chakan'){ //
				$id = input('param.id');
				$res=EscortWxopenGetauthorizerlist::where('id',$id)->field('authorizer_appid,refresh_token')->find();
				$wxopen = new \app\common\WxOpen();
				$res=$wxopen->getPrivacySetting($res['authorizer_appid'],$res['refresh_token']);
				if($res){
					$data['list']=$res;
					$data['status'] = 1;
					$data['msg'] = '更新成功';
					return json($data);exit;
				}else{
					$data['msg'] = '更新失败';
					return json($data);exit;
				}
			}else
			if($type=='yuming'){ //设置域名
				$id = input('param.id');
				$res=EscortWxopenGetauthorizerlist::where('id',$id)->field('authorizer_appid,refresh_token')->find();
				$wxopen = new \app\common\WxOpen();
				$url=getweburl();
				//如果url为空则提示失败
				if(!$url){
					$data['msg'] = '域名为空';
					return json($data);exit;
				}
				//如果域名最后一个字符是/则去掉
				if(substr($url,-1)=='/'){
					$url=substr($url,0,strlen($url)-1);
				}
				$uparr=[
					"action" => "add",
					"requestdomain" => [$url],
					"wsrequestdomain" => [],
					"uploaddomain" => [$url],
					"downloaddomain" => [$url],
					"udpdomain" => [],
					"tcpdomain" => []
				];
				$res=$wxopen->modifyDomain($res['authorizer_appid'],$res['refresh_token'],$uparr);
				if($res && $res['errcode']==0){
					$data['status'] = 1;
					$data['msg'] = '添加成功';
					return json($data);exit;
				}else{
					$data['msg'] = '添加失败';
					return json($data);exit;
				}
			}else
			if($type=='yinsi'){ //更新隐私条款
				$id = input('param.id');
				$res=EscortWxopenGetauthorizerlist::where('id',$id)->field('authorizer_appid,refresh_token')->find();
				$wxopen = new \app\common\WxOpen();
				$res=$wxopen->setPrivacySetting($res['authorizer_appid'],$res['refresh_token']);
				$res=json_decode($res,true);
				if($res && $res['errcode']==0){
					$data['status'] = 1;
					$data['msg'] = '更新成功';
					return json($data);exit;
				}else{
					$data['msg'] = '更新失败';
					return json($data);exit;
				}
			}
			$id = input('param.id');
			if($id){
				$appid=EscortWxopenGetauthorizerlist::where('id',$id)->value('authorizer_appid');
				//引入WxOpen
				$wxopen = new \app\common\WxOpen();
				$res=$wxopen->getAuthInfo($appid);
				if($res){
					//查询是否已经存在  //具体值的意思 https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/authorization-management/getAuthorizerInfo.html
					$exist=Db::name('Escort_wxopen_authinfo')->where('authid',$id)->find();
					if($exist){
						$arr=[
							'nick_name'=>$res['authorizer_info']['nick_name'],
							'user_name'=>$res['authorizer_info']['user_name'],
							'head_img'=>isset($res['authorizer_info']['head_img'])? $res['authorizer_info']['head_img']:'',
							'type' => $res['authorizer_info']['MiniProgramInfo']?1:0,
							'service_type_info'=>$res['authorizer_info']['service_type_info']['id'],
							'verify_type_info'=>$res['authorizer_info']['verify_type_info']['id'],
							'qrcode_url'=>$res['authorizer_info']['qrcode_url'],
							'open_pay'=>$res['authorizer_info']['business_info']['open_pay'],
							'account_status'=>$res['authorizer_info']['account_status'],
						];
						Db::name('Escort_wxopen_authinfo')->where('authid',$id)->update($arr);

						$text = '修改授权用户详情-id='.$id;
						$this->writeActionLog($text);
						$data['msg'] = '修改成功';
					}else{
						//将数据添加到授权用户详情表
						$arr=[
							'authid' => $id,
							'nick_name'=>$res['authorizer_info']['nick_name'],
                            'user_name'=>$res['authorizer_info']['user_name'],
							'head_img'=>isset($res['authorizer_info']['head_img'])? $res['authorizer_info']['head_img']:'',
							'type' => $res['authorizer_info']['MiniProgramInfo']?1:0,
							'service_type_info'=>$res['authorizer_info']['service_type_info']['id'],
							'verify_type_info'=>$res['authorizer_info']['verify_type_info']['id'],
							'qrcode_url'=>$res['authorizer_info']['qrcode_url'],
							'open_pay'=>$res['authorizer_info']['business_info']['open_pay'],
							'account_status'=>$res['authorizer_info']['account_status'],
						];
						Db::name('Escort_wxopen_authinfo')->insert($arr);
						$text = '添加授权用户详情-id='.$id;
						$this->writeActionLog($text);
						$data['msg'] = '添加成功';
					}
					$data['status'] = 1;
					return json($data);exit;
				}
			}
			// $authorizer_appid=input('param.authorizer_appid');
			// $refresh_token=input('param.refresh_token');
			// //$auth_time=input('param.auth_time');
			// $arr=array(
			// 	'authorizer_appid'=>$authorizer_appid,
			// 	'refresh_token'=>$refresh_token,
			// );
			// $id = input('param.id');
			// if ($id){
			// 	$id=EscortWxopenGetauthorizerlist::where('id',$id)->update($arr);
			// 	$text = '修改了授权列表-id='.$id;
			// 	$this->writeActionLog($text);
			// 	$data['status'] = 1;
			// 	return json($data);exit;
			// }
		}
		//引入WxOpen 获取授权地址
		$wxopen = new \app\common\WxOpen();
		$authUrl=$wxopen->getAuthUrl();
		View::assign('authUrl', $authUrl);
		return View::fetch('editgetauthorizerlist');
	}
	public function delgetauthorizerlist(){
 		$data = array('status' => 0,'msg' => '未知错误');
		$array=input("param.id");
		if(!$array){
			$data['msg']='参数错误';return json($data);exit;
		}
		$arr=explode(",",$array);
		for($i=0;$i<count($arr);$i++){
			if($arr[$i]){
				EscortWxopenGetauthorizerlist::where('id',$arr[$i])->delete();
				$text = '删除了授权列表id='.$arr[$i].'的数据';
				$this->writeActionLog($text);
			}
		}
		$data['status']=1;
		return json($data);
	}
	public function draft(){
 		$dao=input('param.dao');
		if(request()->isPost() || $dao==1){
			$page=input('param.page');
			if(!$page){
				$page=1;
			}
			$limit=input('param.limit');
			if(!$limit){
				$limit=10;//每页显示条数
			}
			$where=[];
			$id=input('param.id');
			if($id){
				$where[]=['id','=',$id];
			}
			$draft_id=input('param.draft_id');
			if($draft_id){
				$where[]=['draft_id','like','%'.$draft_id.'%'];
			}
			$user_version=input('param.user_version');
			if($user_version){
				$where[]=['user_version','like','%'.$user_version.'%'];
			}
			$user_desc=input('param.user_desc');
			if($user_desc){
				$where[]=['user_desc','like','%'.$user_desc.'%'];
			}
			$create_time=input('param.create_time');
			if($create_time){
				$where[]=['create_time','like','%'.$create_time.'%'];
			}
			$count = EscortWxopenDraft::where($where)->count();
			if($dao!=1){
				$data=EscortWxopenDraft::where($where)->page($page,$limit)->order('id desc')->select()->toArray();
			}
			if($dao==1){
				$data=EscortWxopenDraft::where($where)->order('id desc')->select()->toArray();
			}
			if($data){
				for($i=0;$i<count($data);$i++){
				}
			}
			if($dao==1){
				$excel = new \PHPExcel(); //引用phpexcel
				$excel->setActiveSheetIndex(0);
				$namex = '代码草稿列表';
				$excel->getActiveSheet()->setTitle($namex); //设置表名
				$excel->getActiveSheet()->getDefaultColumnDimension()->setWidth(20);//所有单元格（列）默认宽度
				$excel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(50);
				$excel->getDefaultStyle()->getFont()->setName('微软雅黑');//字体
				$styleThinBlackBorderOutline = array(
				'borders' => array(
				'allborders' => array( //设置全部边框
				'style' => \PHPExcel_Style_Border::BORDER_THIN //粗的是thick
				)
				),
				);
				// 设置单元格的宽度
				$excel->getActiveSheet()->getDefaultColumnDimension()->setWidth(20);
				$excel->setActiveSheetIndex(0)
				->setCellValue('A1', 'ID')
				->setCellValue('B1', '草稿 id')
				->setCellValue('C1', '版本号')
				->setCellValue('D1', '版本描述')
				->setCellValue('E1', '创建时间')
				;
				$excel->getActiveSheet()->getStyle( 'A1:E1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
				$excel->getActiveSheet()->getStyle( 'A1:E1')->getFill()->getStartColor()->setARGB('FCE4D6');//设置填充颜色
				$cno=count($data)+1;
				$excel->getActiveSheet()->getStyle('A1:E'.$cno)->applyFromArray($styleThinBlackBorderOutline);
				foreach ($data as $k => $v) {
				$excel->getActiveSheet()->setCellValue('A' . ($k + 2), $v['id']."	");
					$excel->getActiveSheet()->setCellValue('B' . ($k + 2), $v['draft_id']);
					$excel->getActiveSheet()->setCellValue('C' . ($k + 2), $v['user_version']);
					$excel->getActiveSheet()->setCellValue('D' . ($k + 2), $v['user_desc']);
					$excel->getActiveSheet()->setCellValue('E' . ($k + 2), $v['create_time']);
				}
				ob_end_clean();
				header('Content-Type: application/vnd.ms-excel');
				header('Content-Disposition: attachment;filename="' . $namex . '.xls"');
				header('Cache-Control: max-age=0');
				$res_excel = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
				$res_excel->save('php://output');exit;
			}
			$res = ["data" => $data,"code"=>0,'message'=>'请求成功','count'=>$count];
			return json($res);
		}
		$permis = $this->getPermissions('Wxopen/draft');
		View::assign('data', $this->actions);
		View::assign('permis', $permis);
		return View::fetch();
	}
	public function adddraft(){
 		if(request()->isPost()){
			$data = array('status' => 0, 'msg' => '未知错误');

			//使用WxOpen获取getTemplateDraftList
			$wxopen = new \app\common\WxOpen();
			$res=$wxopen->getTemplateDraftList();
			if($res){
				$list=$res['draft_list'];
				for($i=0;$i<count($list);$i++){
					$draft_id=$list[$i]['draft_id'];
					$user_version=$list[$i]['user_version'];
					$user_desc=$list[$i]['user_desc'];
					$create_time=date('Y-m-d H:i:s',$list[$i]['create_time']);
					$arr=array(
						'draft_id'=>$draft_id,
						'user_version'=>$user_version,
						'user_desc'=>$user_desc,
						'create_time'=>$create_time,
					);
					//判断是否已经存在
					$exist=EscortWxopenDraft::where('draft_id',$draft_id)->find();
					if($exist){
						//修改
						EscortWxopenDraft::where('draft_id',$draft_id)->update($arr);
						$text = '修改了代码草稿列表-id='.$exist['id'];
						$this->writeActionLog($text);
					}else{
						//添加
						$id=EscortWxopenDraft::insertGetId($arr);
						$text = '添加了代码草稿列表-id='.$id;
						$this->writeActionLog($text);
					}
				}
				$data['status'] = 1;
				return json($data);exit;
			}
		}
		return View::fetch('editdraft');
	}
	public function editdraft(){
 		if(request()->isPost()){
			$data = array('status' => 0, 'msg' => '未知错误');
			$id = input('param.id');
			if(!$id){
				$data['msg']='参数错误';return json($data);exit;
			}
			$draft_id=EscortWxopenDraft::where('id',$id)->value('draft_id');
			//使用WxOpen添加到模板库
			$wxopen = new \app\common\WxOpen();
			$res=$wxopen->addToTemplate($draft_id);
			if($res && $res['errcode']==0){
				//修改状态
				//EscortWxopenDraft::where('id',$id)->update(['status'=>1]);
				$text = '上传了代码草稿列表-id='.$id;
				$this->writeActionLog($text);
				$data['status'] = 1;
				return json($data);exit;
			}
		}
		return View::fetch('editdraft');
	}
	public function deldraft(){
 		$data = array('status' => 0,'msg' => '未知错误');
		$array=input("param.id");
		if(!$array){
			$data['msg']='参数错误';return json($data);exit;
		}
		$arr=explode(",",$array);
		for($i=0;$i<count($arr);$i++){
			if($arr[$i]){
				EscortWxopenDraft::where('id',$arr[$i])->delete();
				$text = '删除了代码草稿列表id='.$arr[$i].'的数据';
				$this->writeActionLog($text);
			}
		}
		$data['status']=1;
		return json($data);
	}
} 